﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MQTTTool.Util
{
	public class JsonUtil
	{
		static string Mqttfilename = "Mqtt.save.taoke";
		static string comfilename = "Com.save.taoke";
		private static JsonUtil jutil;
		public static JsonUtil GetInstance() {
			if (jutil == null)
			{
				return jutil = new JsonUtil();
			}
			return jutil;
		}
		public T GetMqttObj<T>() {
			try
			{
				string path = System.AppDomain.CurrentDomain.BaseDirectory + Mqttfilename;

				using (StreamReader read = new StreamReader(path))
				{
					string jsondata = read.ReadToEnd();
					return JsonConvert.DeserializeObject<T>(jsondata);
				}
			}
			catch (Exception)
			{
				return default(T);

			}
		}
		public void SaveMqttObj(object obj) {
			string value = JsonConvert.SerializeObject(obj);
			string path = System.AppDomain.CurrentDomain.BaseDirectory + Mqttfilename;
			try
			{

				using (StreamWriter writer = new StreamWriter(path)) {
					writer.Write((value));
					writer.Flush();
				}
			}
			catch (Exception)
			{
				throw;
				
			}
		}
		public void SavecompageObj(object obj)
		{
			string value = JsonConvert.SerializeObject(obj);
			string path = System.AppDomain.CurrentDomain.BaseDirectory + comfilename;
			try
			{

				using (StreamWriter writer = new StreamWriter(path))
				{
					writer.Write((value));
					writer.Flush();
				}
			}
			catch (Exception)
			{
				throw;

			}
		}
	}
}
